﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Threading.Tasks;
using UnityEngine.AddressableAssets;
using System;
using System.Linq;
using LitJson;
using SangsTools;

namespace Player
{

    public class Science
    {
        private const string TBLPath = "Addressable/TBL", AddressableName = "ScienceData";
        
        public event System.Action EventOnNumChange;
        public event System.Action EventOnCoefficientChange;//TODO 把改动在事件中用参数传递

        public STScienceData ScienceData { get; private set; }

        private ItemRandom.IItemRandomer randomer;

        private int _scienceNum;
        /// <summary>
        /// 当前有的科技点
        /// </summary>
        public int ScienceNum{ 
            get => _scienceNum;
            set
            {
                _scienceNum = value;

                EventOnNumChange?.Invoke();
            }
        }
        /// <summary>
        /// 全局的需求系数
        /// </summary>
        public float GlobalCoefficient { get; set; }
        private Dictionary<string, float> dictProjectCoefficient=new Dictionary<string, float>();
        /// <summary>
        /// 每个项目的需求系数
        /// </summary>
        public IEnumerable<KeyValuePair<string, float>> ProjectCoefficient => dictProjectCoefficient;
        public (float curCoefficient, STScienceProjectData projectData) this[string tag]
        {
            get
            {
                try
                {
                    return (dictProjectCoefficient[tag], ScienceData.dictPrejectData[tag]);
                }
                catch (Exception)
                {
                    Debug.LogError($"Tag Error {tag}");
                    throw;
                }
            }
        }

        public Science()
        {
            randomer = new ItemRandom.NormalRandomer();
        }

        public async Task InitAsync()
        {
            TextAsset textAsset = await Addressables.LoadAssetAsync<TextAsset>(AddressableName).Task;
            if (textAsset != null && !string.IsNullOrEmpty(textAsset.text))
            {
                try
                {
                    ScienceData = JsonMapper.ToObject<STScienceData>(textAsset.text);
                    foreach (var item in ScienceData.dictPrejectData.Values)
                    {
                        dictProjectCoefficient.Add(item.strItemRandomTag, 1);
                    }

                    GlobalCoefficient = 1;
                }
                catch
                {
                    throw new Exception("-科研-信息表数据异常");
                }
            }
            else
                throw new Exception("-科研-道具信息表加载失败");
        }

        public void Reset()
        {
            ScienceNum = 0;
            GlobalCoefficient = 1;

            var arrTmp = dictProjectCoefficient.Keys.ToArray();
            foreach (var key in arrTmp)
            {
                dictProjectCoefficient[key] = 1;
            }
        }

        public string[] FinishProject(string[] chooseTags)
        {
            if (chooseTags == null || chooseTags.Length == 0)
            {
                Debug.Log("选中标签数组为空");
                return null;
            }

            System.Text.StringBuilder sb = new System.Text.StringBuilder("本次科研选择 tag:");
            foreach (var item in chooseTags)
            {
                sb.Append(item);
                sb.Append(',');
            }
            sb.Remove(sb.Length - 1, 1);
            try
            {
                float chooseCoefficient = 0;
                for (int i = 0; i < chooseTags.Length; i++)
                {
                    string tag = chooseTags[i];
                    //先取当前的倍率
                    chooseCoefficient += dictProjectCoefficient[tag];
                    //然后更新倍率
                    dictProjectCoefficient[tag] *= (float)ScienceData.dictPrejectData[tag].fIncrease;
                }
                //基础 * 全局系数 * 选中系数
                int needScience = (int)(chooseCoefficient * GlobalCoefficient * ScienceData.nBaseScienceNum);
                ScienceNum -= needScience;

                GlobalCoefficient *= (float)ScienceData.fGlobalIncrease;
                EventOnCoefficientChange?.Invoke();
            }
            catch (Exception e)
            {
                Debug.LogError(e);
                throw;
            }

            return randomer?.GetRandomItems(chooseTags, ScienceData.nGetItemOptionCount);
        }

#if UNITY_EDITOR
        public static void SaveTBLData()
        {
            string json = LitJson.JsonMapper.ToJson(GetScienceData());
            //Debug.Log(json.ToUTF8());
            SangsTools.MyJsonTools.SaveJsonFile(json.ToUTF8(), TBLPath, AddressableName);
        }
        private static STScienceData GetScienceData()
        {
            STScienceData scienceData = new STScienceData()
            {
                nBaseScienceNum = 10,
                nBaseGoldNum = 100,
                fGlobalIncrease = 1.2f,
                nGetItemOptionCount=3,
            };

            Dictionary<string, STScienceProjectData> dict = new Dictionary<string, STScienceProjectData>();

            //TODO 加一个纯换钱的项目
            foreach (var item in Item.ItemTypeConst.Types)
            {
                dict.Add(item.type, new STScienceProjectData()
                {
                    strItemRandomTag = item.type,
                    strProjectName = item.name,
                    fIncrease = 1.1f
                });
            }

            scienceData.dictPrejectData = dict;

            return scienceData;
        }
#endif
    }
}
